﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
using NetCoreCMS.Common;
using NetCoreCMS.IServices;
using NetCoreCMS.Models;
using Newtonsoft.Json.Linq;

namespace NetCoreCMS.Web.Areas.Admin.Controllers.Order
{
    public class Express_ListController : ManageController
    {
        private const string WEB_VIEW = "~/Areas/Admin/Views/Order/express_list.cshtml";
        protected int totalCount;
        protected int page;
        protected int pageSize;
        public IExpressService _express { get; set; }
        protected string keywords = string.Empty;
        public override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            base.OnActionExecuting(filterContext);
            if (filterContext.Result != null)
                return;
            ChkAdminLevel("order_express", CMSEnums.ActionEnum.View.ToString()); //检查权限
            this.keywords = Request.Query["keywords"];
            if (int.TryParse(Request.Query["pageNum"], out this.pageSize))
            {
                if (this.pageSize > 0)
                {
                    Response.Cookies.Append("express_page_size", this.pageSize.ToString());
                }
            }
            else
            {
                this.pageSize = GetPageSize(10); //每页数量
            }
            ViewBag.Keywords = this.keywords;
            ViewBag.PageNum = this.pageSize.ToString();
            ViewBag.Page = this.page.ToString();
        }
        //
        // GET: /admin/Express_List/

        public ActionResult Index()
        {
            RptBind("where id>0" + CombSqlTxt(keywords), "sort_id asc,id desc");
            return View(WEB_VIEW);
        }

        [HttpPost]
        public ActionResult SubmitSave()
        {
            ChkAdminLevel("order_express", CMSEnums.ActionEnum.Edit.ToString()); //检查权限
            JObject jobject = JObject.Parse(Request.Form["json"]);
            JToken list = jobject["list"];
            foreach (JToken item in list)
            {
                int id = Convert.ToInt32(item["id"].ToString());
                int sortId = Convert.ToInt32(item["sortId"].ToString());
                _express.UpdateField(id, "sort_id=" + sortId.ToString());
            }
            AddAdminLog(CMSEnums.ActionEnum.Edit.ToString(), "保存配送方式排序"); //记录日志
            string script = JscriptMsg("保存排序成功！", Utils.CombUrlTxt("index", "keywords={0}", this.keywords));
            return Content(script);
        }

        [HttpPost]
        public ActionResult SubmitDelete()
        {
            ChkAdminLevel("order_express", CMSEnums.ActionEnum.Delete.ToString()); //检查权限
            int sucCount = 0;
            int errorCount = 0;
            JObject jobject = JObject.Parse(Request.Form["json"]);
            JToken list = jobject["list"];
            foreach (JToken item in list)
            {
                int id = Convert.ToInt32(item["id"].ToString());
                if (_express.Delete(id))
                {
                    sucCount += 1;
                }
                else
                {
                    errorCount += 1;
                }
            }
            AddAdminLog(CMSEnums.ActionEnum.Delete.ToString(), "删除配送方式成功" + sucCount + "条，失败" + errorCount + "条"); //记录日志
            string script = JscriptMsg("删除成功" + sucCount + "条，失败" + errorCount + "条！", Utils.CombUrlTxt("index", "keywords={0}", this.keywords));
            return Content(script);
        }

        #region 数据绑定=================================
        private void RptBind(string _strWhere, string _orderby)
        {
            int.TryParse(Request.Query["page"], out this.page);
            this.page = this.page <= 0 ? 1 : this.page;
            ViewData["list"] = _express.GetList(this.page, this.pageSize, _strWhere, _orderby, null);
            this.totalCount = _express.RecordCount(_strWhere);
            string pageUrl = Utils.CombUrlTxt("index", "keywords={0}&page={1}", this.keywords, "__id__");
            ViewBag.PageContent = Utils.OutPageList(this.pageSize, this.page, this.totalCount, pageUrl, 8);
        }
        #endregion

        #region 组合SQL查询语句==========================
        protected string CombSqlTxt(string _keywords)
        {
            StringBuilder strTemp = new StringBuilder();            
            if (!string.IsNullOrEmpty(_keywords))
            {
                _keywords = _keywords.Replace("'", "");
                strTemp.Append(" and (title like  '%" + _keywords + "%' or express_code like '%" + _keywords + "%')");
            }

            return strTemp.ToString();
        }
        #endregion

        #region 返回每页数量=============================
        private int GetPageSize(int _default_size)
        {
            int _pagesize;
            if (int.TryParse(Request.Cookies["express_page_size"], out _pagesize))
            {
                if (_pagesize > 0)
                {
                    return _pagesize;
                }
            }
            return _default_size;
        }
        #endregion
    }
}
